package com.justgame.project.service.system.controller;

import com.justgame.project.base.annotation.ProtectAccess;
import com.justgame.project.base.utils.SmsUtils;
import com.justgame.project.cloud.base.entity.WeChatAuthResult;
import com.justgame.project.cloud.common.constant.Result;
import com.justgame.project.cloud.common.util.WeChatUtils;
import com.justgame.project.service.system.controller.form.custom.LoginPostForm;
import com.justgame.project.service.system.controller.form.custom.WxRegisterPostForm;
import com.justgame.project.service.system.entity.SysUserInfo;
import com.justgame.project.service.system.service.ISysUserInfoService;
import com.justgame.project.service.system.vo.UserAuthorizationResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.RequiredArgsConstructor;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;

/**
 *
 * 用户信息表控制器
 *
 * @@tableName sys_user_info
 * @author Zwb
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/sys/user/info")
@Api("用户信息表控制器")
public class SysUserInfoController {
    private final ISysUserInfoService sysUserInfoService;

    @GetMapping("/detail")
    @RequiresPermissions("admin")
    @ApiOperation(value = "通过主键id查询 用户信息表")
    public Result<?> query(@ApiParam("主键id") @NotNull(message = "必须提供需要查询的数据") Long id){
        return Result.ok(sysUserInfoService.getById(id));
    }

    /**
     * 账号登录
     * @param loginForm 登录表单
     */
    @PostMapping("/login")
    @ProtectAccess(value = 10L, message = "请勿频繁登录账号！")
    @ApiOperation("统一登录接口")
    public Result<Object> login(@RequestBody LoginPostForm loginForm) {
        loginForm.paramsCheck();
        UserAuthorizationResult result = loginForm.getLoginType().getLoginHandle().call(sysUserInfoService,loginForm);
        return Result.ok(result);
    }

    @PostMapping("/logout")
    @RequiresAuthentication
    @ApiOperation("退出登录")
    public Result<Object> logout(SysUserInfo sysUserInfo,HttpServletRequest request) {
        return Result.status(sysUserInfoService.logout(sysUserInfo,request));
    }


    @PostMapping("/wx-register")
    @ApiOperation("通过微信授权获取微信绑定手机号")
    public Result<?> getWxPhone(@RequestBody @Validated WxRegisterPostForm form){
        Assert.isTrue(SmsUtils.isMatch(form.getPhoneNumber(),form.getSmsCode()),"验证码错误");
        WeChatAuthResult authResult = WeChatUtils.getWeChatAuthResult(form.getJsCode());
        return Result.ok(sysUserInfoService.wxRegister(form.getPhoneNumber(),authResult));
    }
}